package com.rookie.tool.module.util.transform;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * pdf转图片
 *
 * @author rookie
 */
public class PdfToImage {

    /**
     * 将整个pdf转换成图片
     *
     * @param fullPath     pdf的完整路径，包括文件名
     * @param itemFullPath 转换后的图片放置路径
     */
    public static void transform(String fullPath, String itemFullPath, String type) {
        if (!verifyFilePath(fullPath, itemFullPath)) {
            return;
        }

        String fileName = fullPath.substring(fullPath.lastIndexOf("\\") + 1, fullPath.lastIndexOf("."));
        if (!StringUtils.hasText(type)) {
            return;
        }
        // 将pdf装图片 并且自定义图片得格式大小
        File file = new File(fullPath);
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144);
                String imgName = itemFullPath + fileName + (i + 1) + "." + type;
                ImageIO.write(image, type, new File(imgName));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 自由确定起始页和终止页
     *
     * @param fullPath     pdf的完整路径，包括文件名
     * @param itemFullPath 转换后的图片放置路径
     * @param indexOfStart 开始页  开始转换的页码，从0开始
     * @param indexOfEnd   结束页  停止转换的页码，-1为全部
     */
    public static void transform(String fullPath, String itemFullPath, int indexOfStart, int indexOfEnd, String type) {
        if (!verifyFilePath(fullPath, itemFullPath)) {
            return;
        }

        if (!StringUtils.hasText(type)) {
            return;
        }

        String fileName = fullPath.substring(fullPath.lastIndexOf("\\") + 1, fullPath.lastIndexOf("."));

        // 将pdf装图片 并且自定义图片得格式大小
        File file = new File(fullPath);
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = indexOfStart; i < indexOfEnd; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144);

                String imgName = itemFullPath + fileName + (i + 1) + "." + type;
                ImageIO.write(image, type, new File(imgName));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static boolean verifyFilePath(String fullPath, String itemFullPath) {
        return StringUtils.hasText(fullPath) && StringUtils.hasText(itemFullPath);
    }

    public static void main(String[] args) {
       transform("D:\\g\\【www.zcdby.com】高性能mysql[第2版].pdf","D:\\g\\",26,33,"png");
    }
}
